/**
 * 登录状态管理
 */
import axios from 'axios';
import {EleIframeLayout} from 'ele-admin';
import setting from '@/config/setting';
import util2 from '@/utils/util2'

export default {
  namespaced: true,
  state: {
    token: setting.takeToken(),
    // 当前用户信息
    user: setting.takeUser(),
    // 当前用户权限
    authorities: [],
    // 当前用户角色
    roles: [],
    // 当前用户的菜单
    menus: null,
    // 当前打开的选项卡
    tabs: []
  },
  mutations: {
    // 修改值
    SET(state, obj) {
      state[obj.key] = obj.value;
    },
    // 修改token
    SET_TOKEN(state, obj) {
      setting.cacheToken(obj.token, obj.remember);
      state.token = obj.token;
      if (!obj.token) {
        state.user = {};
        state.token = null;
        state.menus = null;
        state.tabs = [];
        setting.cacheUser();
      }
    },
    // 添加tab
    TAB_PUSH(state, obj) {
      // console.log(obj);
      if(obj.key=='/contacts/contacts' || obj.key=='/chat/chat'){
        return;
      }
      let i = state.tabs.findIndex((d) => d.key === obj.key);
      if (i === -1) {
        state.tabs = state.tabs.concat([obj]);
        return;
      }
      if (obj.fullPath !== state.tabs[i].fullPath) {
        state.tabs = state.tabs.slice(0, i).concat([obj]).concat(state.tabs.slice(i + 1));
      }
    }
  },
  actions: {
    /**
     * 缓存token
     * @param commit
     * @param token {String, {token: String, remember: String}}
     */
    setToken({commit}, token) {
      let remember = true;
      if (typeof token === 'object') {
        remember = token.remember;
        token = token.token;
      }
      commit('SET_TOKEN', {token: token, remember: remember});
    },
    /**
     * 移除token
     * @param commit
     */
    removeToken({commit}) {
      commit('SET_TOKEN', {});
    },
    /**
     * 设置用户信息
     * @param commit
     * @param user {Object} 用户信息
     */
    setUser({commit}, user) {
      setting.cacheUser(user);
      commit('SET', {key: 'user', value: user});
    },
    /**
     * 设置用户权限
     * @param commit
     * @param authorities {Array<String>} 权限
     */
    setAuthorities({commit}, authorities) {
      commit('SET', {key: 'authorities', value: authorities});
    },
    /**
     * 设置用户角色
     * @param commit
     * @param roles {Array<String>} 角色
     */
    setRoles({commit}, roles) {
      commit('SET', {key: 'roles', value: roles});
    },
    /**
     * 设置用户菜单
     * @param commit
     * @param menus {Array<Object>} 菜单
     */
    setMenus({commit}, menus) {
      commit('SET', {key: 'menus', value: menus});
    },
    /**
     * 获取用户菜单路由
     * @param commit
     * @returns {Promise<>} {menus: Array, home: String}
     */
    // getMenus({commit}) {
    //   return new Promise((resolve, reject) => {
    //     if (!setting.menuUrl) {
    //       let menus = setting.menus || [];
    //       commit('SET', {key: 'menus', value: menus});
    //       return resolve({menus: menus});
    //     }
    //     axios.get(setting.menuUrl).then(res => {
    //       let result = setting.parseMenu ? setting.parseMenu(res.data) : res.data;
    //       // 获取用户的信息、角色、权限
    //       if (result.user) {
    //         setting.cacheUser(result.user);
    //         commit('SET', {key: 'user', value: result.user});
    //         // commit('SET', {key: 'roles', value: result.user.roles});
    //         // commit('SET', {key: 'authorities', value: result.user.authorities});
    //       }
    //       // 获取用户的菜单
    //       if (!result.data) {
    //         return reject(new Error(result.msg));
    //       }
    //       // result.data=[];
    //       // result.data.unshift({"menuId":20000,"parentId":0,"title":"通讯录","icon":"my-icon my-icon-addressbook","color":null,"path":"/contacts","component":"/contacts/contacts","target":"_self","uid":null,"hide":0,"sortNumber":0,"authority":null,"menuType":0,"children":[],"checked":null,"open":null,"meta":{"title":"通讯录","icon":"my-icon my-icon-addressbook","hide":0,"active":null},"redirect":"/contacts/contacts"});
    //       result.data.unshift({"menuId":20000,"parentId":0,"title":"通讯录","icon":"my-icon my-icon-addressbook","path":"/contacts","component":null,"target":"_self","children":[{"menuId":20001,"parentId":20000,"title":"通讯录","icon":"my-icon my-icon-addressbook","path":"/contacts/contacts","component":"/contacts/contacts","target":"_self","children":[]}]});
    //       result.data.unshift({"menuId":10000,"parentId":0,"title":"消息","icon":"my-icon my-icon-community","path":"/chat","component":null,"target":"_self","children":[{"menuId":10001,"parentId":10000,"title":"工作台","icon":"el-icon-monitor","path":"/chat/chat","component":"/chat/chat","target":"_self","children":[]}]});
    //
    //       // formatMenus方法主要用于把接口的菜单数据转成带有meta格式的数据
    //       const {menus, homePath, homeTitle} = formatMenus(result.data, setting.parseMenuItem);
    //       if (!setting.homeTitle) {
    //         setting.homeTitle = homeTitle;
    //       }
    //
    //       console.log(menus)
    //       commit('SET', {key: 'menus', value: menus});
    //       resolve({menus: menus, home: homePath});
    //     }).catch(e => {
    //       reject(e);
    //     });
    //   });
    // },
    getMenuRouters({commit, state}) {
      return new Promise((resolve, reject) => {
        if (state.menus) return resolve(menusToRoute2(state.menus));
        if (!setting.menuUrl) {
          commit('SET', {key: 'menus', value: []});
          return resolve(null);
        }
        axios.get(setting.menuUrl).then(res => {
          let menus = setting.parseMenu ? setting.parseMenu(res.data) : res.data.data;
          // menus.unshift({"menuId":20000,"parentId":0,"title":"通讯录","icon":"my-icon my-icon-addressbook","path":"/contacts","target":"_self","children":[{"menuId":20001,"parentId":20000,"title":"通讯录","icon":"my-icon my-icon-addressbook","path":"/contacts/contacts","target":"_self"}]});
          // menus.unshift({"menuId":10000,"parentId":0,"title":"消息","icon":"my-icon my-icon-community","path":"/chat","target":"_self","children":[{"menuId":10001,"parentId":10000,"title":"工作台","icon":"el-icon-monitor","path":"/chat/chat","target":"_self"}]});

          menus.forEach(d => {
            if (!d.redirect) {
              d.redirect = d.children[0].path;
            }
          });
          resolve(menusToRoute2(menus));

          commit('SET', {key: 'menus', value: menus});
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 添加新tab
     * @param commit
     * @param obj {{path: String, title: String}} tab信息
     */
    tabAdd({commit}, obj) {
      commit('TAB_PUSH', obj);
    },
    /**
     * 关闭指定tab
     * @param commit
     * @param state
     * @param key {String}
     * @returns {Promise<>}
     */
    tabRemove({commit, state}, key) {
      return new Promise((resolve) => {
        let index = -1, lastIndex = -1, lastPath, last;
        for (let i = 0; i < state.tabs.length; i++) {
          if (state.tabs[i].key === key || state.tabs[i].fullPath === key) {
            index = i;
            break;
          }
          lastIndex = i;
          last = state.tabs[i];
          lastPath = last.fullPath;
        }
        commit('SET', {key: 'tabs', value: state.tabs.filter((d, i) => i !== index)});
        resolve({lastIndex: lastIndex, lastPath: lastPath, last: last});
      });
    },
    /**
     * 关闭所有tab
     * @param commit
     */
    tabRemoveAll({commit}) {
      commit('SET', {key: 'tabs', value: []});
    },
    /**
     * 关闭左侧tab
     * @param commit
     * @param state
     * @param key {String}
     */
    tabRemoveLeft({commit, state}, key) {
      for (let i = 0; i < state.tabs.length; i++) {
        if (state.tabs[i].key === key) {
          commit('SET', {key: 'tabs', value: state.tabs.slice(i)});
          break;
        }
      }
    },
    /**
     * 关闭右侧tab
     * @param commit
     * @param state
     * @param key {String}
     */
    tabRemoveRight({commit, state}, key) {
      for (let i = 0; i < state.tabs.length; i++) {
        if (state.tabs[i].key === key) {
          commit('SET', {key: 'tabs', value: state.tabs.slice(0, i + 1)});
          break;
        }
      }
    },
    /**
     * 关闭其他tab
     * @param commit
     * @param state
     * @param key {String}
     */
    tabRemoveOther({commit, state}, key) {
      commit('SET', {key: 'tabs', value: state.tabs.filter((d) => d.key === key)});
    },
    /**
     * 修改指定tab标题
     * @param commit
     * @param state
     * @param obj {{path: String, title: String, fullPath: String, closable: Boolean}}
     */
    tabSetTitle({commit, state}, obj) {
      let i = -1;
      if (obj.fullPath) {
        i = state.tabs.findIndex((d) => d.fullPath === obj.fullPath);
      } else if (obj.path) {
        i = state.tabs.findIndex((d) => d.path === obj.path);
      }
      if (i !== -1) {
        const data = Object.assign({}, state.tabs[i]);
        if (typeof obj.title !== 'undefined') {
          data.title = obj.title;
        }
        if (typeof obj.closable !== 'undefined') {
          data.closable = obj.closable;
        }
        const tabs = state.tabs.slice(0, i).concat([data]).concat(state.tabs.slice(i + 1));
        commit('SET', {key: 'tabs', value: tabs});
      }
    }
  }
}
/** 菜单生成路由 */
function menusToRoute2(menus) {
  let route = {path: '/', name: 'main', children: [], redirect: null};
  let parent = '';
  util2.eachTreeData(menus, (item) => {
    if (setting.parseMenuItem) item = setting.parseMenuItem(item);
    item.meta = Object.assign({title: item.title, icon: item.icon,parent:parent,hide:item.hide}, item.meta);
    if (item.path && !item.children) {
      if (!route.redirect) {
        route.redirect = setting.homePath || item.path;
        if (!setting.homeTitle) setting.homeTitle = item.meta.title;
      }
      if(!item.path.startsWith('http://') && !item.path.startsWith('https://') && !item.path.startsWith('//')){
        route.children.push({
          path: item.path, name: item.name || item.path, meta: item.meta,
          component: () => import('@/views' + item.path)
        });
      }
      else{
        item.meta.iframe = item.path;
        item.path = "/iframe/page"+item.menuId;
        route.children.push({
          path: "/iframe/page"+item.menuId, name: item.name || "/iframe/page"+item.menuId, meta: item.meta,
          component:EleIframeLayout
        });
      }

    }
    else{
      parent = item.path;
    }
  });
  // console.log("--------------------------------------------------");
  // console.log(route);
  // console.log("--------------------------------------------------");
  return route;
}
